package com.fans.admin.captcha;


import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import com.fans.common.constant.SysConstant;
import com.fans.common.redis.util.JedisUtils;
import com.fans.common.utils.CaptchaUtils;
import com.fans.common.utils.ServletUtils;

/**
 * @ClassName: CaptchaService
 * @Description: 验证码Service实现
 * @author fanhaohao
 * @date 2019年12月14日 上午10:59:48
 */
@Service
public class CaptchaService {

	/**
	 * @param captchaId
	 * 
	 * @Title：buildCaptcha @Description: 创建验证码 @author: fanhaohao @date
	 * 2020年1月12日 下午12:35:54 @param @return @param @throws Exception @return
	 * byte[] @throws
	 */
	public byte[] buildCaptcha(String captchaId) throws Exception {
        CaptchaUtils.Captcha captcha = CaptchaUtils.createCaptcha(120, 30);
		JedisUtils.setObject(SysConstant.CAPTCHA_KEY + captchaId, captcha.getCode(), 300);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(captcha.getImage(), "jpg", byteArrayOutputStream);
        //定义响应值，写入byte
        byte[] bytes = byteArrayOutputStream.toByteArray();
		buildImageRes(bytes);
        return bytes;
    }
    
    /**
     * 
     * @Title：buildImageRes  
     * @Description: 创建Response
     * @author: fanhaohao
     * @date 2020年1月12日 下午12:33:06 
     * @param @param bytes
     * @param @throws IOException 
     * @return void 
     * @throws
     */
	public static void buildImageRes(byte[] bytes) throws IOException {
    	HttpServletResponse response = ServletUtils.getImageRes();
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(bytes);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

}